package 数据结构专栏.简单级别;

/**
 * @DESC https://leetcode-cn.com/problems/longest-common-prefix/
 * @Author tzq
 * @Date 2020-03-26 09:52
 **/
public class _14_最长公共前缀 {

    //    输入: ["flower","flow","flight"]
    //    输出: "fl"
    public static void main(String[] args) {

        String[] strs = new String[]{"flower", "flow", "flight"};
        System.out.println(longestCommonPrefix2(strs));


    }

    /**
     * 取收个元素做为比较基数，依次和后面的进行比较，如不满足则使基数减少
     *
     * @param strs
     * @return
     */
    public static String longestCommonPrefix(String[] strs) {

        if (strs.length == 0 || strs == null) {
            return "";
        }
        String res = strs[0];
        for (String str : strs) {

            while (str.indexOf(res) != 0) {
                res = res.substring(0, res.length() - 1);
            }
        }


        return res;
    }


    public static String longestCommonPrefix2(String[] strs) {

        if (strs.length == 0 || strs == null) {
            return "";
        }
        String res = strs[0];
        for (int i = 1; i < strs.length; i++) {
            while (strs[i].indexOf(res) != 0) {
                res = res.substring(0, res.length() - 1);
            }
        }


        return res;
    }

}
